package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.cargo.PackService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/packing")
public class PackController extends BaseController {


    @Reference
    private ExportService exportService;
    
    @Reference
    private PackService packService;

    @Reference
    private ExportProductService exportProductService;


    /*
       url:/cargo/pack/list.do
       作用： 进入装箱单列表
       参数： 无
       返回值： cargo/pack/pack-list.jsp

    */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {

        //找到装箱单列表
        PackExample packExample = new PackExample();
        //按照创建时间排序
        packExample.setOrderByClause("create_time desc");
        //添加条件，当前登陆者所属的企业
        packExample.createCriteria().andCompanyIdEqualTo(getLoginUserCompanyId());

        PageInfo<Pack> pageInfo = packService.findByPage(packExample, pageNum, pageSize);
        //2. 存储到域
        System.out.println(pageInfo);
        request.setAttribute("pageInfo", pageInfo);
        return "cargo/pack/pack-list";
    }

    /*
      url:/cargo/pack/toPack.do
      作用： 进入添加装箱单的页面
      参数： id 生成装箱单的购销合同的id，是可能会存在多个id
      返回值： cargo/pack/pack-toPack

   */
    @RequestMapping("/toPack")
    public String toPack(String id) {
        //通过报运单得到报运合同的id
        String[] exportIds = id.split(",");

        Pack pack = new Pack();
        pack.setExportIds(id);
        //找到该装箱单对应的报运合同
        ExportExample exportExample = new ExportExample();
        //添加报运合同的查询添加
        exportExample.createCriteria().andIdIn(Arrays.asList(exportIds));
        List<Export> exportList = exportService.findAll(exportExample);

        if (exportList!=null){
            if (exportList.size()!=1){
                Export export = exportList.get(0);
                String consignee = export.getConsignee();
                String shipmentPort = export.getShipmentPort();
                String destinationPort = export.getDestinationPort();
                for (int i = 1; i < exportList.size(); i++) {
                    Export exporti = exportList.get(i);
                    if (consignee!=exporti.getConsignee() || shipmentPort!=exporti.getShipmentPort() || destinationPort!=exporti.getDestinationPort() ){
                        return "cargo/pack/pack-error";
                    }
                }
            }
        }

        //遍历报运合同，取出合同号去拼接
        String exportNos = "";
        //定义一个变量装箱合同报运的总体积
        Double totalVolume = 0.0;
        //定义一个变量装箱合同报运的总净重
        Double totalNetWeight = 0.0;

        //定义一个变量 装箱合同报运的总毛重
        Double totalGrossWeights=0.0;
        //定义一个变量 装箱费用
        Double packingMoney = 0.0;
        for (Export export : exportList) {
                exportNos += export.getCustomerContract() + " ";
                totalVolume += export.getMeasurements();
                totalGrossWeights += export.getGrossWeights();
                ExportProductExample exportProductExample = new ExportProductExample();
                exportProductExample.createCriteria().andExportIdEqualTo(export.getId());
                List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);
                for (ExportProduct exportProduct : exportProductList) {
                    totalNetWeight += exportProduct.getNetWeight() == null ? 0 : exportProduct.getNetWeight();
                }
                packingMoney += totalGrossWeights * 520;
        }
        //装箱单的状态： 刚生成到装箱单是0，草稿状态的装箱单是不允许装箱，0状态可以拿给委托装箱，1已经装箱的
        pack.setTotalVolume(BigDecimal.valueOf(totalVolume));
        pack.setNetWeights(BigDecimal.valueOf(totalNetWeight));
        pack.setExportNos(exportNos);
        pack.setPackingMoney(BigDecimal.valueOf(packingMoney));
        pack.setGroosWeights(BigDecimal.valueOf(totalGrossWeights));


        //插入装箱单
        request.setAttribute("id",id);
        request.setAttribute("pack",pack);

        return "cargo/pack/pack-toPack";
    }

    /*
       url：/cargo/export/edit.do
       作用：保存添加与保存修改报运单
       参数：报运单对象
       返回值： 报运单列表
    */
    @RequestMapping("/edit")
    public String edit(Pack pack){
        //补充数据，因为这些数据是来自于登陆者
        String companyId = getLoginUserCompanyId();
        String companyName= getLoginUserCompanyName();
        pack.setCompanyId(companyId);
        pack.setCompanyName(companyName);
        //报运单的创建人
        pack.setCreateBy(getLoginUser().getId());
        //报运单创建人所属的部门
        pack.setCreateDept(getLoginUser().getDeptId());

        //1.判断export是否携带id过来，如果没有携带则是添加
        if(StringUtils.isEmpty(pack.getPackingListId())){
            packService.save(pack);
        }
        return "redirect:/cargo/export/list.do";
    }

    /*
        url:/cargo/packing/delete.do?id=8a7e8412584c739201584c7433c50000
        作用：删除装箱单
        参数： id 装箱单的id
        返回值：/cargo/packing/lsit.do
     */
    @RequestMapping("/delete")
    public String delete(String id) {
        Pack pack = packService.findById(id);
        if (pack.getState()==0) {
            packService.delete(id);
        }
        return "redirect:/cargo/packing/list.do";
    }


    /*
       url：/cargo/packing/toView.do?id=31df2a93-10ae-404e-a83f-4225119d8600
       作用：查看装箱单
       参数：id 装箱单的id
       返回值：cargo/pack/pack-view
    */
    @RequestMapping("/toView")
    public String toView(String id){
        Pack pack = packService.findById(id);
        //存储到请求域中
        request.setAttribute("pack",pack);
        return "cargo/pack/pack-view";
    }

}
